#include <REGX52.H>

sbit ONEWIRE_DQ = P3^7;

bit one_wire_init()
{
    unsigned char i, ackBit;
    // 屏蔽中断，因为时序不会等待中断
    EA = 0;
    ONEWIRE_DQ = 1;
    ONEWIRE_DQ = 0;
    // Delay 500μs
	i = 247;
	while (--i) {}
    ONEWIRE_DQ = 1;
    // Delay 70μs
	i = 32;
	while (--i) {}
    ackBit = ONEWIRE_DQ;
    // Delay 500μs
	i = 247;
	while (--i) {}
    EA = 1;
    return ackBit;  // 0表应答，1表非应答
}

void one_wire_sendbit(unsigned char Bit)
{
    unsigned char i;
    EA = 0;
    // 发送跟在init调用结束DQ为1后，故先拉低电平
    ONEWIRE_DQ = 0;
    // Delay 10μs
    i = 4;
	while (--i) {}
    ONEWIRE_DQ = Bit;
    // Delay 50μs
    i = 24;
	while (--i) {}
    ONEWIRE_DQ = 1;
    EA = 1;
}

unsigned char one_wire_receivebit(void)
{
    unsigned char i, Bit;
    EA = 0;
    ONEWIRE_DQ = 0;
    // Delay 5μs
    i = 2;
	while (--i) {}
    ONEWIRE_DQ = 1;
    // Delay 5μs
    i = 2;
	while (--i) {}
    ONEWIRE_DQ = 1;
    Bit = ONEWIRE_DQ;
    // Delay 50μs
    i = 24;
	while (--i) {}
    EA = 1;
    return Bit;
}

void one_wire_sendbyte(unsigned char byte)
{
    unsigned char i;
    for (i = 0; i < 8; i++)
    {
        one_wire_sendbit(byte & (0x01 << i));
    }
}

unsigned char one_wire_receivebyte(void)
{
    unsigned char i, byte = 0x00;
    for (i = 0; i < 8; i++)
    {
        if (one_wire_receivebit())
        {
            byte |= (0x01 << i);
        }
    }
    return byte;
}